package com.kefu.web.im.config.web.handle;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.kefu.web.im.config.IMDataContext;
import com.kefu.web.im.config.web.message.ChatMessage;
import com.kefu.web.im.config.web.message.SeatServiceMessage;
import com.kefu.web.im.config.web.message.SeatStatusMessage;
import com.kefu.web.im.config.web.router.OutMessageRouter;
import com.kefu.web.im.domain.MessageOutContent;
import com.kefu.web.im.domain.SeatStatus;
import com.kefu.web.im.domain.SeatUser;
import com.kefu.web.im.domain.SeatUserTask;
import com.kefu.web.im.netty.client.NettyClients;
import com.kefu.web.im.service.quene.ServiceQuene;
import com.kefu.web.im.util.CommonTools;

/**
 * 座位事件处理器
 * 
 * @author chenkw
 *
 */
public class SeatEventHandler {
	protected SocketIOServer server;

	@Autowired
	public SeatEventHandler(SocketIOServer server) {
		this.server = server;
	}

	@OnConnect
	public void onConnect(SocketIOClient client) {
		String user = client.getHandshakeData().getSingleUrlParam("userid");
		if (!StringUtils.isBlank(user)) {
			client.set("seatno", user);
			NettyClients.getInstance().putSeatEventClient(user, client);
		}
	}

	// 添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息
	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {
		String user = client.getHandshakeData().getSingleUrlParam("userid");
		String orgi = client.getHandshakeData().getSingleUrlParam("orgi");
		if (!StringUtils.isBlank(user)) {
			try {
				// TODO 下线逻辑
//				OnlineUserUtils.offline(user, orgi);
			} catch (Exception e) {
				e.printStackTrace();
			}
			NettyClients.getInstance().removeSeatEventClient(user, client.getSessionId().toString());
		}
	}

	// 消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
	@OnEvent(value = "service")
	public void onEvent(SocketIOClient client, AckRequest request, SeatServiceMessage data) {

	}

	// 消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
	@OnEvent(value = "status")
	public void onEvent(SocketIOClient client, AckRequest request, SeatStatusMessage data) {

	}

	// 消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息，且给自己发送消息
	@OnEvent(value = "message")
	public void onEvent(SocketIOClient client, AckRequest request, ChatMessage data) {
		String user = client.getHandshakeData().getSingleUrlParam("userid");
		// TODO
//    	SeatUser seatUser = (SeatUser) CacheHelper.getAgentUserCacheBean().getCacheObject(data.getTouser(), data.getOrgi());
		SeatUser seatUser = null;
		MessageOutContent outMessage = new MessageOutContent();
		outMessage.setMessage(data.getMessage());
		outMessage.setMessageType(IMDataContext.MediaTypeEnum.TEXT.toString());
		outMessage.setCalltype(IMDataContext.CallTypeEnum.OUT.toString());
		outMessage.setSeatUser(seatUser);
		outMessage.setSnsAccount(null);
//    	AgentStatus agentStatus = (AgentStatus) CacheHelper.getAgentStatusCacheBean().getCacheObject(data.getUserid(), data.getOrgi()) ;
		SeatStatus seatStatus = null;
		if (seatStatus == null) {
			// TODO
//    		agentUser = IMDataContext.getContext().getBean(AgentUserRepository.class).findByIdAndOrgi(data.getTouser() , data.getOrgi()) ;
			try {
				ServiceQuene.serviceFinish(seatUser, data.getOrgi());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (seatUser != null && user != null && user.equals(seatUser.getSeatno())) {
			data.setId(CommonTools.getUUID());
			data.setContextid(seatUser.getContextid());

			data.setAgentserviceid(seatUser.getSeatserviceid());
			data.setCreater(seatUser.getSeatno());

			data.setMsgtype(IMDataContext.MediaTypeEnum.TEXT.toString());

			data.setCalltype(IMDataContext.CallTypeEnum.OUT.toString());
			if (!StringUtils.isBlank(seatUser.getSeatno())) {
				data.setTouser(seatUser.getUserid());
			}
			data.setChannel(seatUser.getChannel());

			data.setUsession(seatUser.getUserid());

			outMessage.setContextid(seatUser.getContextid());
			outMessage.setFromUser(data.getUserid());
			outMessage.setToUser(data.getTouser());
			outMessage.setChannelMessage(data);
			if (seatStatus != null) {
				data.setUsername(seatStatus.getUsername());
				outMessage.setNickName(seatStatus.getUsername());
			} else {
				outMessage.setNickName(data.getUsername());
			}
			outMessage.setCreatetime(data.getCreatetime());
			// TODO
//    		AgentUserTaskRepository agentUserTaskRes = IMDataContext.getContext().getBean(AgentUserTaskRepository.class) ;
//    		SeatUserTask seatUserTask = agentUserTaskRes.getOne(agentUser.getId()) ;
			SeatUserTask seatUserTask = null;
			seatUserTask.setLastgetmessage(new Date());

			seatUserTask.setReptime(null);
			seatUserTask.setReptimes("0");

//    		agentUserTaskRes.save(agentUserTask) ;

			/**
			 * 保存消息
			 */
//    		IMDataContext.getContext().getBean(ChatMessageRepository.class).save(data) ;

			client.sendEvent(IMDataContext.MessageTypeEnum.MESSAGE.toString(), data);

			if (!StringUtils.isBlank(data.getTouser())) {
				OutMessageRouter router = null;
				router = (OutMessageRouter) IMDataContext.getContext().getBean(seatUser.getChannel());
				if (router != null) {
					router.handler(data.getTouser(), IMDataContext.MessageTypeEnum.MESSAGE.toString(),
							seatUser.getAppid(), outMessage);
				}
			}
		} else if (user != null && seatUser != null && !user.equals(seatUser.getSeatno())) {
			client.sendEvent(IMDataContext.MessageTypeEnum.END.toString(), seatUser);
		}
	}
}